package cn.edu.pet.servlet;

import cn.edu.pet.entity.Admin;
import cn.edu.pet.entity.User;
import cn.edu.pet.repo.AdminRepo;
import cn.edu.pet.repo.UserRepo;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        PrintWriter writer = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");
        String captcha = req.getParameter("captcha");
        if(!req.getSession().getAttribute("AUTH_CODE").equals(captcha)){
            String json = mapper.writeValueAsString("验证码错误!");
            writer.write(json);
            return;
        }
        try {
            if ("1".equals(type)) {
                //管理员
                Admin admin = AdminRepo.getInstance().getByName(username);
                if (admin.getId() != null && admin.getPassword().equals(password)) {
                    req.getSession().setAttribute("user", admin);
                    String json = mapper.writeValueAsString("登陆成功");
                    writer.write(json);
                    return;
                }
            } else {
                User user = UserRepo.getInstance().selectByName(username);
                if (user.getId() != null && user.getPassword().equals(password)) {
                    req.getSession().setAttribute("user", user);
                    String json = mapper.writeValueAsString("登陆成功");
                    writer.write(json);
                    return;
                }
            }
            String json = mapper.writeValueAsString("账号或密码错误！");
            writer.write(json);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

